<?php

namespace app\controller;


use app\service\UserLuckService;
use app\service\UserSpaceTrainService;
use support\Response;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\facade\Db;

//用户扭蛋抽奖控制器
class UserLuckController extends Base
{

    //查询抽奖次数
    public function index(): Response
    {
        $res = (new UserLuckService())->index();
        return $this->json($res);
    }


    /**
     * 查询扭蛋池
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public function pool(): Response
    {
        //类型
        $type = $this->request->get('type', LOTTERY_TYPE['免费池']);
        $res = (new UserLuckService())->pool($this->user_id, $type);
        return $this->json($res);
    }


    //抽奖
    public function draw(): Response
    {
        $type = $this->request->post('type', LOTTERY_TYPE['免费池']);
        $num = $this->request->post('num', 1);
        // 启动事务
        Db::startTrans();
        try {
            $res = (new UserLuckService())->draw($this->user_id, $type, $num);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            return $this->fail("数据库异常");
        }
        return $this->json($res);

    }


}